//
//  PANetworkManager.m
//  PAFramework
//
//  Created by Gavin Zhang on 7/17/13.
//  Copyright (c) 2013 Gavin Zhang. All rights reserved.
//

#import "PANetworkManager.h"
#import "PAHttpRequest.h"
#import "ASIDataDecompressor.h"
#import "PADataCenter.h"
#import "OpenUDID.h"
static PANetworkManager *_sharedInstance;

@interface PANetworkManager ()
@property(nonatomic, copy)NSString *sessionId;
@property(nonatomic, strong)NSDictionary *resultInfosDic;
@property(nonatomic, copy)NSString *clientId;

@property(nonatomic, strong)NSDictionary *serverInterfacesDic;
@end

@implementation PANetworkManager
- (id)init
{
    self = [super init];
    if (self) {
        self.clientId = [OpenUDID value];
        self.sessionId = @"初始化为占位";
        
        [self loadConfigInfos];
    }
    return self;
}
#pragma mark - singleton
+(PANetworkManager *)sharedInstance
{
    if (!_sharedInstance) {
        _sharedInstance = [[super allocWithZone:NULL] init];
    }
    return _sharedInstance;
}
+(id)allocWithZone:(NSZone *)zone
{
    return [PANetworkManager sharedInstance];
}
-(id)copyWithZone:(NSZone *)zone
{
    return self;
}
- (void)loadConfigInfos
{
    NSString * path = [[NSBundle mainBundle] pathForResource:@"resultCodeInfos" ofType:@"plist"];
    NSDictionary * temp = [NSDictionary dictionaryWithContentsOfFile:path];
    self.resultInfosDic = temp;
    path = [[NSBundle mainBundle] pathForResource:@"serverInterfaces" ofType:@"plist"];
    temp = [NSDictionary dictionaryWithContentsOfFile:path];
    self.serverInterfacesDic = temp;
}
- (void)reqAsynParamDic:(NSDictionary *)paramDic userInfo:(NSDictionary *)userInfo delegate:(id<PANetworkDelegate>)delegate
{
    NSString *operationType = [paramDic objectForKey:k_operationType];
    NSURL *serverURL = [NSURL URLWithString:[self.serverInterfacesDic objectForKey:operationType]];
    NSMutableDictionary * postDic = [[NSMutableDictionary alloc] initWithObjectsAndKeys:self.sessionId,k_sessionId,self.clientId,k_clientId,nil];
    [postDic addEntriesFromDictionary:paramDic];
    
    PAHttpRequest *req = [PAHttpRequest requestWithURL:serverURL];
    req.paNetDelegate = delegate;
    req.delegate = self;
    req.timeOutSeconds = 60;
    req.bufferData = [NSMutableData data];
    NSMutableDictionary *addedUserInfo = [NSMutableDictionary dictionaryWithDictionary:userInfo];
    [addedUserInfo setObject:operationType forKey:k_operationType];
    req.userInfo = addedUserInfo;
    req.operationType = operationType;
    NSString *json = nil;
	[req addRequestHeader:@"Content-Type" value:@"application/x-www-form-urlencoded"];
    if ([NSJSONSerialization isValidJSONObject:postDic]){
        NSError *error;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:postDic options:NSJSONWritingPrettyPrinted error:&error];
        json =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

    }
    NSLog(@"\noperationType:%@\nreqJson:%@",req.operationType,json);
	[req appendPostData:[json dataUsingEncoding:NSUTF8StringEncoding]];
	[req startAsynchronous];
}

#pragma mark - ASIHTTPRequestDelegate implementation
- (void)requestStarted:(ASIHTTPRequest *)request
{
    if ([request isKindOfClass:[PAHttpRequest class]]){
        PAHttpRequest *req = (PAHttpRequest *)request;
        if (req.paNetDelegate && [req.paNetDelegate respondsToSelector:@selector(paRequestStarted:)]) {
            [req.paNetDelegate paRequestStarted:req.userInfo];
        }
//        else{
//            UIActivityIndicatorView *loadingV = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
//            [loadingV setCenter:CGPointMake (132.0f, 60.0f)];
//            [loadingV startAnimating];
//        }
    }
    
}
//- (void)request:(ASIHTTPRequest *)request didReceiveResponseHeaders:(NSDictionary *)responseHeaders
//{}
//- (void)request:(ASIHTTPRequest *)request willRedirectToURL:(NSURL *)newURL
//{}
- (void)requestFinished:(ASIHTTPRequest *)request
{
    PADataCenter *dataCenter = [PADataCenter sharedInstance];
    if ([request isKindOfClass:[PAHttpRequest class]]) {
        PAHttpRequest *req = (PAHttpRequest *)request;
        if (req.paNetDelegate && [req.paNetDelegate respondsToSelector:@selector(paRequestFinished:)]) {
            [req.paNetDelegate paRequestFinished:req.userInfo];
        }
        
        NSError *error = nil;
        NSData *data = req.isResponseCompressed ? [ASIDataDecompressor uncompressData:req.bufferData error:&error] : req.bufferData;
        if (error) {
            NSLog(@"解压错误");
        }else{
            NSDictionary *rspDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
            NSMutableDictionary *addedResponsDic = [NSMutableDictionary dictionaryWithDictionary:rspDic];
            [addedResponsDic setObject:req.operationType forKey:k_operationType];
            NSString *resultCodeStr = [addedResponsDic objectForKey:k_resultCode];
            
            int resultCode = [resultCodeStr intValue];
            if (1000 == resultCode) {
                /*
                 * 预计此处做一些集中处理
                 */
                NSLog(@"\noperationType:%@\nresponsDic:%@",req.operationType,addedResponsDic);
                NSString *sessionId = [addedResponsDic objectForKey:k_sessionId];
                if(sessionId && (![sessionId isEqualToString:@""]))self.sessionId = sessionId;
                
                if ([req.operationType isEqualToString:@"op_query_balance"]) {
                    dataCenter.selfInfo.balance = [[rspDic objectForKey:k_balance] doubleValue];
                    dataCenter.selfInfo.availableBalance = [[rspDic objectForKey:K_availableBalance] doubleValue];
                    
                }else if ([req.operationType isEqualToString:@"op_query_last_payment_info"]){
                    [dataCenter updateTimeLineInfoDic:rspDic];
                }else if ([req.operationType isEqualToString:@"op_query_bank_card"]){
                    [dataCenter updateBankCardInfo:rspDic];
                }
                
                if (req.paNetDelegate && [req.paNetDelegate respondsToSelector:@selector(paRequestRespons:userInfo:)]) {
                    [req.paNetDelegate paRequestRespons:addedResponsDic userInfo:req.userInfo];
                }
            }
            else{
                /*
                 * 可解析的各种错误
                 */
                if (1011 == resultCode) {
                    
                }
                else if (1024 == resultCode){
                    [[NSNotificationCenter defaultCenter] postNotificationName:NOT_NeedRelogin object:nil];
                }
                else if(1025 == resultCode){
                }
                else{
                    NSString *errorCodeInfoStr = [self.resultInfosDic objectForKey:resultCodeStr];
                    if (nil == errorCodeInfoStr) errorCodeInfoStr = @"网络异常，请重新登陆";
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:errorCodeInfoStr delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil , nil];
                    [alert show];
                }
                NSLog(@"\noperationType:%@\nresultCode:%@",req.operationType,resultCodeStr);
                if (req.paNetDelegate && [req.paNetDelegate respondsToSelector:@selector(paRequestAccurateFailed:userInfo:)]) {
                    [req.paNetDelegate paRequestAccurateFailed:resultCode userInfo:req.userInfo];
                }
            }
            
        }
        
    }
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
    NSLog(@"requestFailed\n%@",request.error);
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"网路异常" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil , nil];
    [alert show];
}
//- (void)requestRedirected:(ASIHTTPRequest *)request
//{}
- (void)request:(ASIHTTPRequest *)request didReceiveData:(NSData *)data
{
    if ([request isKindOfClass:[PAHttpRequest class]]) {
        PAHttpRequest *req = (PAHttpRequest *)request;
        [req.bufferData appendData:data];
    }
}
//- (void)authenticationNeededForRequest:(ASIHTTPRequest *)request
//{}
//- (void)proxyAuthenticationNeededForRequest:(ASIHTTPRequest *)request
//{}


#pragma mark - UIAlertViewDelegate 
- (void)alertViewCancel:(UIAlertView *)alertView
{
    [alertView dismissWithClickedButtonIndex:0 animated:YES];
}

@end
